<template>
  <div class="kafka-topic-no-update-form">
    <el-form label-width="140px" :model="localValue">
      <!-- Kafka集群配置 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><List /></el-icon>
          <span>Kafka集群配置</span>
        </div>
        <el-form-item label="选择Kafka集群" required>
          <ServiceConfigSelector
            v-model="clusterIdSelector"
            service-type="kafka"
            placeholder="请选择Kafka集群"
          />
        </el-form-item>
      </section>

      <!-- Topic选择 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><List /></el-icon>
          <span>Topic选择</span>
        </div>
        <el-form-item label="Topic列表">
          <el-select
            v-model="localValue.topic_selection.topic_names"
            multiple
            filterable
            allow-create
            placeholder="请选择Topic（留空表示查询所有）"
            :loading="topicsLoading"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
            @visible-change="handleTopicsVisibleChange"
            @change="emitParams"
          >
            <el-option
              v-for="topic in topicOptions"
              :key="topic"
              :label="topic"
              :value="topic"
            />
          </el-select>
        </el-form-item>
      </section>

      <!-- 时间阈值配置 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><Clock /></el-icon>
          <span>时间阈值</span>
        </div>
        <el-form-item label="告警阈值">
          <el-checkbox-group v-model="localValue.time_thresholds.thresholds" @change="emitParams">
            <el-checkbox label="1_day">1天未更新</el-checkbox>
            <el-checkbox label="7_days">7天未更新</el-checkbox>
            <el-checkbox label="1_month">1月未更新</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排序方式">
          <el-checkbox v-model="localValue.time_thresholds.sort_by_staleness" @change="emitParams">
            按未更新时间排序
          </el-checkbox>
        </el-form-item>
      </section>

      <!-- 显示字段 -->
      <section class="form-section">
        <div class="section-title">
          <el-icon><Filter /></el-icon>
          <span>显示字段</span>
        </div>
        <el-checkbox-group v-model="localValue.display_fields" @change="emitParams">
          <el-checkbox
            v-for="field in displayFieldOptions"
            :key="field.value"
            :label="field.value"
          >
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>
      </section>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, watch, ref } from 'vue'
import { Filter, List, Clock } from '@element-plus/icons-vue'
import ServiceConfigSelector from '../../shared/ServiceConfigSelector.vue'
import api from '@/utils/api'

interface TopicNoUpdateParams {
  kafka_cluster_config: { cluster_id: number | null }
  topic_selection: { topic_names: string[] }
  time_thresholds: {
    thresholds: string[]
    sort_by_staleness: boolean
  }
  display_fields: string[]
}

const props = defineProps<{
  modelValue: TopicNoUpdateParams | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: TopicNoUpdateParams): void
}>()

const defaultValue = (): TopicNoUpdateParams => ({
  kafka_cluster_config: { cluster_id: null },
  topic_selection: { topic_names: [] },
  time_thresholds: {
    thresholds: ['1_day'],
    sort_by_staleness: true
  },
  display_fields: ['topic_name', 'partition_id', 'last_message_time', 'hours_no_update', 'status']
})

const localValue = reactive<TopicNoUpdateParams>({
  ...defaultValue(),
  ...(props.modelValue || {})
})

// Computed属性用于ServiceConfigSelector
const clusterIdSelector = computed({
  get: () => localValue.kafka_cluster_config.cluster_id ?? undefined,
  set: (value: number | undefined) => {
    localValue.kafka_cluster_config.cluster_id = value ?? null
    emitParams()
  }
})

// Topic选项
const topicOptions = ref<string[]>([])
const topicsLoading = ref(false)

// 当集群选择变化时，加载Topic列表
watch(
  () => localValue.kafka_cluster_config.cluster_id,
  async (newClusterId) => {
    if (newClusterId) {
      await fetchTopics(newClusterId)
    } else {
      topicOptions.value = []
    }
  }
)

const fetchTopics = async (clusterId: number) => {
  try {
    topicsLoading.value = true
    const response = await api.get('/reports/kafka-topics', {
      params: { config_id: clusterId }
    })
    if (response.data.success) {
      topicOptions.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取Topic列表失败', error)
  } finally {
    topicsLoading.value = false
  }
}

const handleTopicsVisibleChange = async (visible: boolean) => {
  if (visible && topicOptions.value.length === 0 && localValue.kafka_cluster_config.cluster_id) {
    await fetchTopics(localValue.kafka_cluster_config.cluster_id)
  }
}

const displayFieldOptions = [
  { value: 'topic_name', label: 'Topic名称' },
  { value: 'partition_id', label: '分区ID' },
  { value: 'last_message_time', label: '最后消息时间' },
  { value: 'latest_offset', label: '最新Offset' },
  { value: 'hours_no_update', label: '未更新时长(小时)' },
  { value: 'status', label: '状态' }
]

const emitParams = () => {
  emit('update:modelValue', JSON.parse(JSON.stringify(localValue)))
}

watch(() => props.modelValue, (val) => {
  if (val) {
    Object.assign(localValue, defaultValue(), val)
  }
}, { deep: true })
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}
</style>
